import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:wu_you/data/repository/user_repository.dart';
import 'package:wu_you/l10n/messages.dart';
import 'package:wu_you/model/user/user_model.dart';
import 'package:wu_you/res/colors.dart';
import 'package:wu_you/state/bloc/http_bloc.dart';
import 'package:wu_you/state/bloc/user_bloc.dart';
import 'package:wu_you/utils/error_handler.dart';
import 'package:wu_you/utils/navigator_util.dart';
import 'package:wu_you/utils/utils.dart';
import 'package:wu_you/widgets/http_list_widget.dart';
import 'package:wu_you/utils/extension_utils.dart';
import 'package:toast/toast.dart';

///地址管理
class AddressManagerPage extends StatefulWidget{
  final int index;
  AddressManagerPage({Key key,this.index = 0}):super(key: key);
  @override
  AddressManagerPageState createState() => AddressManagerPageState();
}
class AddressManagerPageState extends State<AddressManagerPage>{

  String _selectedId = "0";
  BuildContext _ctx;
  var message;
  @override
  Widget build(BuildContext context) {
    message = AppLocalizations.of(context);
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: Text("${message['address1']}"),
      ),
      body: HttpListWidget<AddressModel, AddressListBloc>(
        creator: (context) => AddressListBloc(),
        onObtainData: (context, page) {
           _ctx = context;
           BlocProvider.of<AddressListBloc>(context).add(PageSizeHttpEvent(1,100));
        },
        successBuilder: (context, data) {
          if (_selectedId == "0") {
            data.forEach((element) {
              if (element.isdefault == "1") {
                _selectedId = element.id;
              }
            });
          }
           return ListView.builder(
               itemBuilder: (context,index){
                 AddressModel item = data[index];
                 return Container(
                   child: Column(
                     children: [
                       ListTile(
                         contentPadding: EdgeInsets.only(left: 15,right: 15,top: 12),
                         leading: Column(
                           mainAxisSize: MainAxisSize.min,
                           crossAxisAlignment: CrossAxisAlignment.start,
                           children: [
                             Row(
                               mainAxisSize: MainAxisSize.min,
                               children: [
                                 Text("${item.name}    ${item.mobile}",style: TextStyle(fontSize: 16),),
                                 Offstage(
                                   offstage: item.isdefault == "1" ? false : true,
                                   child: Container(
                                     width: 31,
                                     height: 18,
                                     padding: EdgeInsets.symmetric(horizontal: 4),
                                     margin: EdgeInsets.only(left: 4),
                                     decoration: BoxDecoration(
                                       color: AppColors.primaryColor,
                                       borderRadius: BorderRadius.circular(4),
                                     ),
                                     child: Text(
                                       "${message['address4']}",
                                       style: TextStyle(fontSize: 11, color: Colors.white),
                                     ),
                                   ),
                                 )
                               ],
                             ),
                             SizedBox(height: 6,),
                             Text("${item.detailed_address}",style: TextStyle(fontSize: 16),)
                           ],
                         ),
                         trailing: Offstage(
                           offstage: widget.index == 1 ? false : true,
                           child: Image.asset(Utils.getImgPath("ic_pay_circle"),width: 20,height: 20,fit: BoxFit.fill,).addGesture(() {
                             if(widget.index == 1){
                               Navigator.of(context).pop(item);
                             }
                           }),
                         )
                       ),
                       SizedBox(height: 8,),
                       Divider(),
                       Row(
                         mainAxisAlignment: MainAxisAlignment.spaceBetween,
                         children: [
                           Row(
                             mainAxisSize: MainAxisSize.min,
                             children: [
                               SizedBox(
                                 width: 30,
                                 height: 30,
                                 child: Radio(
                                   value: item.id,
                                   groupValue: _selectedId,
                                   onChanged: (v){
                                     _changeSelected(v,item);
                                   },
                                 ),
                               ),
                               Text(
                                 "${message['address2']}",
                                 style: TextStyle(fontSize: 15, color: AppColors.textHintColor),
                               ),
                             ],
                           ),


                           Row(
                             mainAxisSize: MainAxisSize.min,
                             children: [
                               Image.asset(Utils.getImgPath("ic_user_address_delete"),width: 18,height: 18,),
                               SizedBox(width: 2,),
                               Text("${message['address3']}",style: TextStyle(color: AppColors.textHintColor),)
                             ],
                           ).addGesture(() {
                             showCupertinoDialog(
                                 context: context,
                                 builder: (context) {
                                   return CupertinoAlertDialog(
                                     title: Text('${message['address12']}'),
                                     content: Text('${message['address13']}'),
                                     actions: <Widget>[
                                       CupertinoDialogAction(child: Text('${message['address14']}'),onPressed: (){
                                         Navigator.pop(context);
                                       },),
                                       CupertinoDialogAction(child: Text('${message['address15']}'),onPressed: (){
                                         LoadingApi.func(UserRepository().deleteReceiveAddress(item.id), context,complete: (v){
                                           ToastUtils.show("${message['Success']}", context);
                                           Navigator.pop(context);
                                           BlocProvider.of<AddressListBloc>(_ctx).add(PageSizeHttpEvent(1,100));
                                         },error: (e){
                                           ToastUtils.show("$e", context);
                                         });
                                       },),
                                     ],
                                   );
                                 });
                           }),
                         ],
                       ).addPadding(EdgeInsets.all(12)),
                       SizedBox(height: 8,),
                       Divider(thickness: 6,color: HexColor("#F4F4F4"),)
                     ],
                   ),
                 );
               },
               itemCount: data.length
           );
        }
      ),
      bottomNavigationBar:SafeArea(
          top: false,
          bottom: true,
          left: false,
          right: false,
          child: Container(
              padding: EdgeInsets.symmetric(horizontal: 0),
              height: 50,
              width: double.infinity,
              child: GestureDetector(
                onTap: (){
                  NavigatorUtil.navigateToPage(context, AddressAddPage()).then((value) {
                    if(value != null){
                      BlocProvider.of<AddressListBloc>(_ctx).add(PageSizeHttpEvent(1,100));
                    }
                  });
                },
                child: Container(
                  height: double.infinity,
                  alignment: Alignment.center,
                  child: Text(
                    '+${message['address5']}',
                    style: TextStyle(color: Colors.white),
                  ),
                  color: AppColors.primaryColor,
                ),
              )
          ),
        )
    );
  }


  void _changeSelected(value,AddressModel model) {
    if (_selectedId == value) {
      return;
    }
    String postIndex = "0";
    if(model.isdefault == "0"){
      postIndex = "1";
    }
    setState(() {
      _selectedId = value;
    });
    UserRepository().updateReceiveAddress(id:model.id).then((value) {
      BlocProvider.of<AddressListBloc>(_ctx).add(PageSizeHttpEvent(1,100));
    }).catchError((error) {
      ErrorHandler.handleError(error, action: (msg) {
        Toast.show(msg, context);
      });
    });

  }
}



///添加收货地址
class AddressAddPage extends StatefulWidget{
  final AddressModel model;
  AddressAddPage({Key key,this.model}):super(key: key);
  @override
  AddressAddPageState createState() => AddressAddPageState();
}
class AddressAddPageState extends State<AddressAddPage>{
  String _consigneeName = '';
  String _consigneeMobile = '';
  String _detailAddress = '';
  bool _switchValue = false;


  @override
  void initState() {
    super.initState();
    var model = widget.model;
    if (model != null) {
      _consigneeName = model.name;
      _consigneeMobile = model.mobile;
      _detailAddress = model.detailed_address;
    }
  }
  var message;
  @override
  Widget build(BuildContext context) {
    message = AppLocalizations.of(context);
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: Text(widget.model != null ? "修改收货地址" :"${message['address5']}"),
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [
            TextField(
              style: Theme.of(context).textTheme.headline6,
              maxLines: 1,
              textAlignVertical: TextAlignVertical.center,
              textInputAction: TextInputAction.next,
              keyboardType: TextInputType.text,
              autofocus: false,
              maxLength: 16,
              onChanged: (value) {
                this._consigneeName = value;
              },
              controller: TextEditingController(text: _consigneeName),
              decoration: InputDecoration(
                fillColor: Colors.transparent,
                prefixIcon: Align(
                  alignment: Alignment.centerLeft,
                  child: Text("${message['address6']}", textAlign: TextAlign.start, style: Theme.of(context).textTheme.headline6),
                ),
                prefixIconConstraints: BoxConstraints.loose(Size(80, 50)),
                filled: true,
                border: OutlineInputBorder(
                  borderSide: BorderSide.none,
                ),
                counterText: '',
                hintText: "${message['address9']}",
                hintStyle: Theme.of(context).textTheme.bodyText1,
              ),
            ).addPadding(EdgeInsets.only(left: 15,right: 12)),
            Divider(),
            TextField(
              style: Theme.of(context).textTheme.headline6,
              maxLines: 1,
              textAlignVertical: TextAlignVertical.center,
              textInputAction: TextInputAction.next,
              keyboardType: TextInputType.phone,
              autofocus: false,
              onChanged: (value) {
                this._consigneeMobile = value;
              },
              controller: TextEditingController(text: _consigneeMobile),
              decoration: InputDecoration(
                fillColor: Colors.transparent,
                prefixIcon: Align(
                  alignment: Alignment.centerLeft,
                  child: Text("${message['address7']}", textAlign: TextAlign.start, style: Theme.of(context).textTheme.headline6),
                ),
                prefixIconConstraints: BoxConstraints.loose(Size(80, 50)),
                filled: true,
                border: OutlineInputBorder(
                  borderSide: BorderSide.none,
                ),
                counterText: '',
                hintText: "${message['address10']}",
                hintStyle: Theme.of(context).textTheme.bodyText1,
              ),
            ).addPadding(EdgeInsets.only(left: 15,right: 12)),
            Divider(),
            TextField(
              style: Theme.of(context).textTheme.headline6,
              maxLines: 1,
              textAlignVertical: TextAlignVertical.center,
              textInputAction: TextInputAction.next,
              keyboardType: TextInputType.text,
              autofocus: false,
              onChanged: (value) {
                this._detailAddress = value;
              },
              controller: TextEditingController(text: _detailAddress),
              decoration: InputDecoration(
                // isCollapsed: true,
                // contentPadding: EdgeInsets.symmetric(horizontal: 8, vertical: 20),//内容内边距，影响高度
                fillColor: Colors.transparent,
                prefixIcon: Align(
                  alignment: Alignment.centerLeft,
                  child: Text("${message['address8']}", textAlign: TextAlign.start, style: Theme.of(context).textTheme.headline6),
                ),
                prefixIconConstraints: BoxConstraints.loose(Size(80, 50)),
                filled: true,
                border: OutlineInputBorder(
                  borderSide: BorderSide.none,
                ),
                counterText: '',
                hintText: "${message['address11']}",
                hintStyle: Theme.of(context).textTheme.bodyText1,
              ),
            ).addPadding(EdgeInsets.only(left: 15,right: 12,bottom: 5)),
            Divider(thickness: 8,color: HexColor("#F4F4F4"),),
            // ListTile(
            //   leading: Text("默认地址",style: Theme.of(context).textTheme.headline6),
            //   title: Text("每次下单会默认使用该地址",style: Theme.of(context).textTheme.bodyText1),
            //   trailing: CupertinoSwitch(
            //     value: _switchValue,
            //     activeColor: AppColors.primaryColor, // 选中时 轨道颜色
            //     thumbColor: Colors.white, // 滑块颜色
            //     trackColor: HexColor("#999999"), // 未选中时 轨道颜色
            //     dragStartBehavior: DragStartBehavior.down,
            //     onChanged: (value) {
            //       _switchValue = value;
            //       setState(() {});
            //     },
            //   ),
            // ),
            Divider(),
          ],
        ),
      ),
      bottomNavigationBar:SafeArea(
          top: false,
          bottom: true,
          left: false,
          right: false,
          child: Container(
              padding: EdgeInsets.symmetric(horizontal: 0),
              height: 50,
              width: double.infinity,
              child: GestureDetector(
                onTap: (){
                  _addAddress();
                },
                child: Container(
                  height: double.infinity,
                  alignment: Alignment.center,
                  child: Text(
                    '${message['cp6']}',
                    style: TextStyle(color: Colors.white),
                  ),
                  color: AppColors.primaryColor,
                ),
              )
          ),
        )
    );
  }

  _addAddress(){
    if(_consigneeName == ""){
      ToastUtils.show("${message['address9']}", context);
      return;
    }
    if(_consigneeMobile == ""){
      ToastUtils.show("${message['address10']}", context);
      return;
    }
    if(_detailAddress == ""){
      ToastUtils.show("${message['address11']}", context);
      return;
    }
    closeKeyboard(context);
    // int defaultStatus = 0;
    // if(_switchValue){
    //   defaultStatus = 1;
    // }else{
    //   defaultStatus = 0;
    // }
    AddressModel am = AddressModel();

    // am.defaultStatus = defaultStatus;
    am.detailed_address = _detailAddress;
    am.name = _consigneeName;
    am.mobile = _consigneeMobile;


    if(widget.model != null){  ///修改
      am.id = widget.model.id;
      // LoadingApi.func(MallRepository.editReceiveAddress(am), context,complete: (v){
      //   ToastUtils.show("修改成功", context);
      //   Navigator.of(context).pop(1);
      // },error: (e){
      //   ToastUtils.show("$e", context);
      // });
    }else{///新增
      LoadingApi.func(UserRepository().addReceiveAddress(_consigneeName,_consigneeMobile,_detailAddress), context,complete: (v){
        ToastUtils.show("${message['Success']}", context);
        Navigator.of(context).pop(1);
      },error: (e){
        ToastUtils.show("$e", context);
      });
    }
  }
}